package com.briup.day40;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

import org.junit.Test;

public class EncodingConversion {
	
	@Test
	public void conversion1() throws Exception {
		
		String path = "src/com/briup/day40/poem.txt";
		FileInputStream fis = new FileInputStream(path);
		InputStreamReader isr = new InputStreamReader(fis,"UTF-8");
		
		String path1 = "src/com/briup/day40/poem_gbk.txt";
		FileOutputStream fos = new FileOutputStream(path1);
		OutputStreamWriter osw = new OutputStreamWriter(fos,"GBK");
		
		char[] cbuf = new char[1024] ;
		int len = -1;
		while ((len = isr.read(cbuf)) != -1) {
			osw.write(cbuf, 0, len);;
		}
		

		osw.close();
		isr.close();
		
		System.out.println("Sucessful!");

		
	}
	
	@Test
	public void conversion2() throws Exception {
		String path = "src/com/briup/day40/poem.txt";
		FileInputStream fis = new FileInputStream(path);
		InputStreamReader isr = new InputStreamReader(fis,"UTF-8");
		
		String string = "";
		char[] cbuf = new char[1024] ;
		int len = -1;
		while ((len = isr.read(cbuf)) != -1) {
			string += new String(cbuf, 0, len);
		}
		
		FileOutputStream fos = new FileOutputStream(path);
		OutputStreamWriter osw = new OutputStreamWriter(fos,"GBK");
		
		osw.write(string);
		

		osw.close();
		isr.close();
		
		System.out.println("Sucessful!");

	}
	
	@Test
	public void conversion3() throws Exception {
		String path = "src/com/briup/day40/poem.txt";
		File file = new File(path);
		
		File tempFile = new File(file.getParent(), "temp");
		
		FileInputStream fis = new FileInputStream(file);
		InputStreamReader isr = new InputStreamReader(fis,"UTF-8");
		
		FileOutputStream fos = new FileOutputStream(tempFile);
		OutputStreamWriter osw = new OutputStreamWriter(fos,"GBK");
		
		
		char[] cbuf = new char[1024] ;
		int len = -1;
		while ((len = isr.read(cbuf)) != -1) {
			osw.write(cbuf, 0, len);
		}
		
		osw.flush();
		
		file.delete();
		
		tempFile.renameTo(file);
		
		

		

		osw.close();
		isr.close();
		
		System.out.println("Sucessful!");

	}
	

}
